package curso.maven.prototipos.prototipoweb.servlet;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.jar.Attributes;
import java.util.jar.Manifest;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import curso.maven.prototipos.prototipoweb.util.LeitorManifest;

public class InicializadorVersaoAplicacao implements ServletContextListener {
	@Override
	public void contextInitialized(ServletContextEvent eventoInicializacao) {
		ServletContext contextoWeb = eventoInicializacao.getServletContext();
		Manifest manifest = lerManifest(contextoWeb);
		publicarVersaoAplicacao(contextoWeb, manifest);
	}
	
	private void publicarVersaoAplicacao(ServletContext contextoWeb, Manifest manifest) {
		Attributes atributos = manifest.getMainAttributes();
		String versaoAplicacao = atributos.getValue("Implementation-Version");
		String buildAplicacao = atributos.getValue("Implementation-Build");
		String numeroVersaoCompleto = valorPadrao(versaoAplicacao, "Desenv") + ":" + valorPadrao(buildAplicacao, "");
		contextoWeb.setAttribute("versaoAplicacao", numeroVersaoCompleto);
	}
	
	private String valorPadrao(String valor, String padrao) {
		return valor != null ? valor : padrao;
	}
	
	private Manifest lerManifest(ServletContext contextoWeb) {
		try {
			URL urlManifest = contextoWeb.getResource("/META-INF/MANIFEST.MF");
			if (urlManifest == null) {
				System.err.println("Manifest inexistente");
				return new Manifest();
			}
			LeitorManifest leitorManifest = new LeitorManifest();
			return leitorManifest.ler(urlManifest);
		} catch (MalformedURLException e) {
			System.err.println("Erro ao ler manifest");
			e.printStackTrace();
			return new Manifest();
		}
	}

	@Override
	public void contextDestroyed(ServletContextEvent eventoFinalizacao) {
	}
}
